package com.applications.codemash;

import java.util.List;
import java.util.Map;

import com.applications.codemash.core.BaseActivity;
import com.applications.codemash.core.Session;
import com.applications.codemash.core.eventhandlers.FlingGestureDetector;
import com.applications.codemash.core.eventhandlers.ListViewItemClickListener;
import com.applications.codemash.database.SessionStartDbAdapter;
import com.applications.codemash.groupers.*;
import com.applications.codemash.utility.*;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.ViewFlipper;

public class CodeMash extends BaseActivity implements Runnable
{
	private ViewFlipper flipper;
	private GestureDetector mGestureDetector;
	
	private Handler handler = new Handler() {
        public void handleMessage(Message msg)
        {
        	LoadInterface();
        	hideProgresDialog();
        }
	};
    
    private final OnTouchListener mScreenTouch = new OnTouchListener()
    {
    	public boolean onTouch(View v, MotionEvent event)
        {
    		mGestureDetector.onTouchEvent(event);
    		return false;
        }
    };
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.session_list);
    	
    	if (CustomContext.getDbAdapter() == null)
    		CustomContext.setDbAdapter(new SessionStartDbAdapter(this));
    	
    	flipper = (ViewFlipper)findViewById(R.id.mainFlipper);
    	
    	if (!CustomContext.getIsDataLoaded())
    	{
	    	Thread thread = new Thread(this);
		    thread.start();
		    
		    showProgressDialog(getString(R.string.app_name), getString(R.string.loadingConferenceInformationDialogMessage));
    	}
    	
    	
	    mGestureDetector = new GestureDetector(this, new FlingGestureDetector(flipper, this));
        mGestureDetector.toString();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.session_list_menu, menu);
        return true;
    }
    
    @Override
	 public boolean onOptionsItemSelected(MenuItem item)
	 {
    	if (item.getItemId() == R.id.menuListQuit)
    	{
    		finish();
    	}
    	else
    	{
	    	switch (item.getItemId())
			{
				case R.id.menuViewByTechnology:
					CustomContext.setCurrentGrouping(new SessionListGroupByTechnology());
					CustomContext.setCurrentSessionKey(new SessionKeyForTechnology());
					break;
				case R.id.menuViewByTrack:
					CustomContext.setCurrentGrouping(new SessionListGroupByTrack());
					CustomContext.setCurrentSessionKey(new SessionKeyForTrack());
					break;
				case R.id.menuViewByDifficulty:
					CustomContext.setCurrentGrouping(new SessionListGroupByDifficulty());
					CustomContext.setCurrentSessionKey(new SessionKeyForDifficulty());
					break;
				case R.id.menuViewBySpeaker:
					CustomContext.setCurrentGrouping(new SessionListGroupBySpeaker());
					CustomContext.setCurrentSessionKey(new SessionKeyForSpeaker());
					break;
				case R.id.menuViewByDate:
					CustomContext.setCurrentGrouping(new SessionListGroupByDay());
					CustomContext.setCurrentSessionKey(new SessionKeyForDate());
					break;
				default:
					break;
			}
			
	    	setGenerator(CustomContext.getCurrentSessionKey());
	    	SessionListGrouper grouping = new SessionListGrouper(CustomContext.getSessionCache(),
	    			CustomContext.getCurrentGrouping());
			Map<String, List<Session>> listMapping = grouping.getMap();
			LoadInterfaceForMap(listMapping);
    	}
		return true;
	 }
    
    @Override
	public void run()
	{
    	CustomContext.getSessionCache();
    	CustomContext.getSpeakerCache();
	    handler.sendEmptyMessage(0);
	}
    
    private void LoadInterface()
    {
    	setGenerator(CustomContext.getCurrentSessionKey());
    	SessionListGrouper grouper = new SessionListGrouper(CustomContext.getSessionCache(), CustomContext.getCurrentGrouping());
    	Map<String, List<Session>> listMapping = grouper.getMap();
    	LoadInterfaceForMap(listMapping);
    }
    
    private void LoadInterfaceForMap(Map<String, List<Session>> listing)
    {
    	int index = 0;
    	LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
    	for (String key : listing.keySet())
    	{
    		View view = null;
    		if (index < flipper.getChildCount())
    		{
    			view = flipper.getChildAt(index);
	    	}
    		else
    		{
    			view = inflater.inflate(R.layout.group_template, null);
    			((ListView)view.findViewById(R.id.listView)).setOnTouchListener(mScreenTouch);
    			((ListView)view.findViewById(R.id.listView)).setOnItemClickListener(new ListViewItemClickListener(this));
    			flipper.addView(view);
	    	}
	    		
    		new CustomListAdapter<Session>(listing.get(key), this, (ListView)view.findViewById(R.id.listView));
    		index++;
    	}
    	
    	ClearRemainingViewsFromFlipper(index);
    	flipper.setDisplayedChild(0);
    	SetWindowTitle();
    }

	private void ClearRemainingViewsFromFlipper(int index)
	{
		int childCount = flipper.getChildCount();
		for (int i=index; i<childCount; i++)
		{
			flipper.removeViewAt(index);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void SetWindowTitle()
	{
		ListView lstView = (ListView)flipper.getChildAt(0).findViewById(R.id.listView);
		CustomListAdapter<Session> adapter = (CustomListAdapter<Session>)lstView.getAdapter();
		Session firstSession = adapter.getData().get(0);
		setWindowTitle(firstSession);
	}
}